﻿#ifndef XRTCCLIENT_STREAM_WEBRTC_STREAM_H_
#define XRTCCLIENT_STREAM_WEBRTC_STREAM_H_

#include <string>

#include <api/peer_connection_interface.h>

#include "xrtc/xrtc_defines.h"

namespace xrtc {

class XRTCPusher;
class XRTCPlayer;

class WebRTCStream : public webrtc::PeerConnectionObserver {
public:
    WebRTCStream(XRTCPusher* xrtc_pusher,std::string uid, const std::string roomId);
    WebRTCStream(XRTCPlayer* xrtc_puller, std::string uid, const std::string roomId);
    virtual ~WebRTCStream();

    bool Init();
    void CreateOffer();
    void CreateAnswer();
    
    void SetLocalOffer(webrtc::SessionDescriptionInterface* desc);
    void SetLocalAnswer(webrtc::SessionDescriptionInterface* desc);
    
    void SetRemoteOffer(const std::string& offer);
    void SetRemoteAnswer(const std::string& answer);

    void AddIceCandidate(std::string sdp_mid, int sdp_mlineindex, std::string sdp);
    void SendAnswer(std::string const answer);
    void SendOffer(std::string const offer);

    sigslot::signal2<WebRTCStream*, const std::string&>
        SignalAnswerReady;
    sigslot::signal2<WebRTCStream*, XRTCStreamState>
        SignalStreamState;
    sigslot::signal2<WebRTCStream*,
        rtc::scoped_refptr<webrtc::RtpReceiverInterface>>
        SignalNewTrack;


private:
    // PeerConnectionObserver
    virtual void OnSignalingChange(
        webrtc::PeerConnectionInterface::SignalingState new_state) override;
    virtual void OnDataChannel(
        rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) override;
    virtual void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override;
    virtual void OnIceGatheringChange(
        webrtc::PeerConnectionInterface::IceGatheringState new_state) override;
    virtual void OnConnectionChange(
        webrtc::PeerConnectionInterface::PeerConnectionState new_state) override;

    virtual void OnAddTrack(
        rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver,
        const std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>& streams) override;

protected:
    std::string const uid_;
    std::string roomId_;
    std::string remoteUid_;

    XRTCPusher* xrtc_pusher_ = nullptr;
    XRTCPlayer* xrtc_player_ = nullptr;

    rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> pc_factory;
    rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc;
};

} // namespace xrtc

#endif // XRTCCLIENT_STREAM_WEBRTC_STREAM_H_